package com.omega.controller;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.omega.constants.ApplicationConstants;
import com.omega.entity.Item;
import com.omega.service.BrandService;
import com.omega.service.ItemService;
import com.omega.vo.EntityListVO;
import com.omega.vo.ItemListVO;

@Controller
@RequestMapping(value = "/admin/item")
public class ItemController {

	@Autowired
	BrandService brandService;
	@Autowired
	ItemService itemService;
	
	@RequestMapping(value = "/addItem", method = RequestMethod.GET)
	public String showAddNewItemForm(Model model){
		ItemListVO itemListVO = EntityListVO.getItemsListVO();
		model.addAttribute(ApplicationConstants.BRAND_NAMES, brandService.loadAllBrands());
		model.addAttribute(ApplicationConstants.ITEM_LIST_VO, itemListVO);
		return ApplicationConstants.ADD_NEW_ITEM_VIEW;
	}
	
	@RequestMapping(value = "/addItem", method = RequestMethod.POST)
	public String submitNewItemForm(@ModelAttribute(ApplicationConstants.ITEM_LIST_VO)ItemListVO itemListVO) {
		for (Iterator<Item> iterator = itemListVO.getItemList().iterator(); iterator.hasNext();) {
			Item item = (Item) iterator.next();
			System.out.println("BrandId: " +item.getBrand().getbrandId());
			if(! StringUtils.isEmpty(item.getItemName()))
				itemService.addItem(item);		
		}		
		return ApplicationConstants.REDIRECT_ITEMS_VIEW;
	}
	
	@RequestMapping(value = "/viewItems", method = RequestMethod.GET)
	public String viewItemPage(Model model){
		model.addAttribute(ApplicationConstants.ITEM_NAMES, itemService.loadAllItems());
		return ApplicationConstants.ITEM_NAMES_VIEW;
	}
	
	@RequestMapping(value = "/editItem/{itemId}", method = RequestMethod.GET)
	public String showEditItemForm(@PathVariable("itemId") String itemId, Model model) {
		Item item = itemService.loadById(Integer.parseInt(itemId));
		model.addAttribute(ApplicationConstants.BRAND_NAMES, brandService.loadAllBrands());
		model.addAttribute(ApplicationConstants.ITEM_OBJ, item);
		return ApplicationConstants.EDIT_ITEM_VIEW;
	}
	
	@RequestMapping(value = "/editItem/{itemId}", method = RequestMethod.POST)
	public String submitEditItemForm(@PathVariable("itemId") String itemId, @ModelAttribute(ApplicationConstants.ITEM_OBJ) Item item, BindingResult result,
			Model model, HttpServletRequest request) {
		itemService.updateItem(item);		
		return ApplicationConstants.REDIRECT_ITEMS_VIEW;
	}
}
